#include "Mutex.hpp"
#include <unistd.h>

int gval = 1000;
using namespace MutexModule;
Mutex mutex;

void* routine(void* args)
{
    char* name = (char*)args;
    while(true)
    {
        //mutex.Lock();
        MutexGuard guard(mutex);
        if(gval > 0)
        {
            usleep(1000);
            printf("%s buy a ticket, there are %d tickets\n", name, gval);
            gval--;
            //mutex.Unlock();
        }
        else
        {
            //mutex.Unlock();
            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_t tid1, tid2, tid3, tid4;
    pthread_create(&tid1, nullptr, routine, (void*)"thread1");
    pthread_create(&tid2, nullptr, routine, (void*)"thread2");
    pthread_create(&tid3, nullptr, routine, (void*)"thread3");
    pthread_create(&tid4, nullptr, routine, (void*)"thread4");

    pthread_join(tid1, nullptr);
    pthread_join(tid2, nullptr);
    pthread_join(tid3, nullptr);
    pthread_join(tid4, nullptr);
    return 0;
}